package com.atgm.mall.gmmailmember.exception;

import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.MemberException;
import com.atgm.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class MemberExceptionHandler {

    @ExceptionHandler(value = MemberException.class)
    public R handlerMemnberException(MemberException e) {
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerParamException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer stringBuffer = new StringBuffer("校验失败: ");
        for (FieldError fieldError : fieldErrors) {
            stringBuffer.append("[" + fieldError.getDefaultMessage() + "]");
        }
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), stringBuffer.toString());
    }

}
